# encoding=utf-8
"""
响应对象业务校验
"""
import logging

from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings

from zc_core.middlewares.proxies.proxy_facade import ProxyFacade
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request
logger = logging.getLogger(__name__)


class BizValidator(BaseValidateMiddleware):

    def __init__(self):
        super(BizValidator, self).__init__()
        settings = get_project_settings()
        self.proxy_facade = ProxyFacade(settings)

    def validate_item(self, request, response, spider):
        proxy = request.meta['proxy']
        if '对不起，系统检测到您的ip' in response.text and proxy:
            proxy = proxy.replace('http://', '').replace('https://', '')
            self.proxy_facade.pool.remove_proxy(proxy)
            logger.info('反爬: [%s]' % proxy)
            return retry_request(request)

        if 'class="xiajia"' in response.text:
            sku_id = request.meta.get('skuId')
            raise IgnoreRequest('下架：%s' % sku_id)

        return response
